<template>
  <div class="maintenancePage">
    <q-dialog full-width v-model="eventLogDialog">
      <EventLog mode="order" :order="orderId"></EventLog>
    </q-dialog>
    <div class="order-extra-area row justify-between">
      <div class="page-header">{{ order?.order_no }}</div>
     <!--  <q-btn
        v-if="order"
        flat
        style="width: 5rem; padding: 0; height: 0"
        icon="history"
        @click="eventLogDialog = true"
      ></q-btn> -->
    </div>
  
    <div class="row my-card">
      <div class="col-5 p-status">
        <q-card-section class="q-pa-sm">
          <div class="row" v-if="parts&&order">
            <div class="p-status-field">
              <div class="col-12 fal">
                <div class="p-status-field "><span class="weight q-px-sm">
                  Order Status -
                </span>
              </div>
              <div class="text-center">
                <div class="status-box" :class="getStatusColor(orderStatus)">
                  <!-- <q-tooltip class="bg-indigo" :offset="[10, 10]">
                    {{ orderStatus }}
                  </q-tooltip> -->
                </div>
                {{ orderStatus }}
              </div>
  
                <q-btn
                  v-if="parts"
                  class="default-btn"
                  style="width: 10rem; padding: 0; margin-left: 1rem; height: 0"
                  @click="orderDetailDialog = true"
                  >... Detail</q-btn
                >
              </div>
              <div class="col-12 fal q-pa-sm">
                <div>
                  <span class="weight"> Stock Code: </span>
                  {{ parts.stock_code }}
                </div>
              </div>
              <div class="col-12 fal q-pa-sm">
                <div>
                  <span class="weight"> Short Description: </span>
                  {{ parts.description }}
                </div>
              </div>
              <div class="col-12 fal q-pa-sm">
                <div>
                  <span class="weight"> Serial No: </span>
                  {{ parts.serial_no }}
                  <ObsolescenceTip v-if="parts&&parts.obsolescence==1"></ObsolescenceTip>
  
                </div>
              </div>
              <div class="fal col-12 q-pa-sm">
                <div>
                  <span class="weight"> Defit from Car: </span>
                  {{ order.location }}
                </div>
              </div>
              <div class="fal col-12 q-pa-sm">
                <div>
                  <span class="weight"> Workgroup: </span>
                  {{ order.workgroup }}
                </div>
              </div>
              <div class="fal col-12 q-pa-sm">
                <div>
                  <span class="weight"> System: </span>
                  {{ parts.system }}
                </div>
              </div>
  
              <div class="fal col-12 q-pa-sm" v-if="order.complete_by_username">
                <div>
                  <span class="weight"> Completed by: </span>
                  {{ order.complete_by_username }}
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
      </div>
      <div class="col-7">
        <!-- <PartsMap :item="parts" v-if="parts && parts.is_parent"></PartsMap> -->
        <PartsMap
          ref="repairOrderPartsMap"
          mode="order"
          :item="parts"
          :stock-code="parts.stock_code"
          :order-id="orderId"
          v-if="parts && parts.is_parent"
        ></PartsMap>
      </div>
  
      <q-dialog full-height v-model="orderDetailDialog">
        <OrderDetailPage
          v-if="parts"
          :part-id="parts?.id"
          :order-id="orderId"
          @close="orderDetailDialog = false"
          @submit="()=>afterEditOrderDetail()"
        ></OrderDetailPage>
      </q-dialog>
  
      <div class="col-12">
        <q-stepper
          flat
          v-model="step"
          header-nav
          ref="stepper"
          animated
          alternative-labels
          active-icon="none"
          class="card-radius"
        >
          <q-step
            :name="1"
            v-if="parts && parts.is_parent && checkStatus && showPartDetail"
            title="Part detail"
            icon="list"
            active-color="indigo-8"
          >
            <PartDetailTable
              @updateChecked="updateChecked"
              @update="updateData"
              :stock-code="parts.stock_code"
              :isReadOnly="isReadOnly"
              :order-id="orderId"
              :editable="true"
              :checked="checked"
            ></PartDetailTable>
          </q-step>
  
          <!--  <q-step
  
                active-color="indigo-8"
              :name="2"
                title="Task"
                :icon="`img:${url}/src/assets/style/task.png`"
              >
              123
            </q-step> -->
  
          <q-step
            active-color="indigo-8"
            :name="parts?.is_parent == false ? 1 : 2"
            title="Maintenance"
            :icon="`img:${maintenanceUrl}`"
            :disable="!checked"
            style="padding: 0"
            
          >
            <q-tabs
              v-model="tab"
              dense
              class="text-grey q-pa-md"
              active-color="indigo-8"
              activeBgColor="white"
              align="justify"
              narrow-indicator
              no-caps
              mobile-arrows
            >
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="curTask"
                label="Current Task"
              >
                <q-badge
                  v-if="checkStatus && checkStatus.current_task.outstanding"
                  color="red"
                  floating
                  rounded
                  >{{ checkStatus.current_task.outstanding }}</q-badge
                >
              </q-tab>
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="history"
                label="History"
              >
              </q-tab>
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="S/W version"
                label="Software"
              >
                <q-badge
                  v-if="checkStatus && checkStatus.software.outstanding"
                  color="red"
                  floating
                  rounded
                  >{{ checkStatus.software.outstanding }}</q-badge
                >
              </q-tab>
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="H/W version"
                label="Hardware"
              >
                <q-badge
                  v-if="checkStatus && checkStatus.hardware.outstanding"
                  color="red"
                  floating
                  rounded
                  >{{ checkStatus.hardware.outstanding }}</q-badge
                >
              </q-tab>
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="edoc"
                label="EDOC"
              >
                <q-badge
                  v-if="checkStatus && checkStatus.edoc.outstanding"
                  color="red"
                  floating
                  rounded
                  >{{ checkStatus.edoc.outstanding }}</q-badge
                >
              </q-tab>
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="htReplacement"
                label="Hard Time Replacement"
              >
                <q-badge
                  v-if="
                    checkStatus && checkStatus.hard_time_replacement.outstanding
                  "
                  color="red"
                  floating
                  rounded
                  >{{ checkStatus.hard_time_replacement.outstanding }}</q-badge
                >
              </q-tab>
  
              <q-tab
                :disable="!checked && parts?.is_parent"
                name="impWork"
                label="Imp Work"
              >
                <q-badge
                  v-if="checkStatus && checkStatus.improvement_work.outstanding"
                  color="red"
                  floating
                  rounded
                  >{{ checkStatus.improvement_work.outstanding }}</q-badge
                >
              </q-tab>
            </q-tabs>
  
            <q-tab-panels
              v-model="tab"
              animated
              style="width: auto"
              class="card-radius"
            >
              <q-tab-panel name="curTask">
                <q-card-section>
                  <TaskTable
                    v-if="parts"
                    :stock_code="parts.stock_code"
                    :parent="parts.is_parent"
                    @update="initCheckStatus"
                    :order-id="orderId"
                    :isReadOnly="isReadOnly"
                    role="tester"
                    display="cur_tab"
                    isHideCol
                  ></TaskTable>
  
                  <!-- <TaskTable
                  v-if="parts"
                  :stock_code="parts.stock_code"
                  :parent="false"
                  @update="initCheckStatus"
                  :order-id="orderId"
                  role="tester"
                  ></TaskTable> -->
                </q-card-section>
              </q-tab-panel>
  
              <q-tab-panel v-if="parts&&order" name="history">
                <q-card-section>
                    <OrderHistoryTable
                      :is-parent="parts.is_parent"
                      :serial_no="parts.serial_no"
                      :isReadOnly="isReadOnly"
                      :stock-code="parts.stock_code"
                      :mode="'order'"
                      :order_id="order.id"
                    ></OrderHistoryTable>
                </q-card-section>
              </q-tab-panel>
  
              <q-tab-panel name="S/W version" style="height: auto">
                <q-card-section>
                  <VerCheckTable
                    class="q-pa-sm"
                    :isReadOnly="isReadOnly"
                    v-if="parts"
                    :repair-order="order ? order.id : 0"
                    :stock-code="parts?.stock_code"
                    name="sw"
                    @update="updateData"
                  ></VerCheckTable>
                </q-card-section>
              </q-tab-panel>
  
              <q-tab-panel name="H/W version" style="height: auto">
                <q-card-section>
                  <VerCheckTable
                    class="q-pa-sm"
                    :isReadOnly="isReadOnly"
                    v-if="parts"
                    :repair-order="order ? order.id : 0"
                    name="hw"
                    :stock-code="parts?.stock_code"
                    @update="updateData"
                  ></VerCheckTable>
                </q-card-section>
              </q-tab-panel>
  
              <q-tab-panel name="edoc">
                <q-card-section>
                  <EdocTable
                    @update="updateData"
                    :isReadOnly="isReadOnly"
                    :order-id="orderId"
                    class="q-ma-md"
                  ></EdocTable>
                </q-card-section>
              </q-tab-panel>
  
              <q-tab-panel name="htReplacement">
                <q-card-section>
                  <OrderHardTimeReplacement
                    v-if="parts"
                    :isReadOnly="isReadOnly"
                    :orderId="orderId"
                    :stock-code="parts?.stock_code"
                    :order-part-id="parts.id"
                    @update="updateData"
                  ></OrderHardTimeReplacement>
                </q-card-section>
              </q-tab-panel>
  
              <q-tab-panel name="impWork">
                <q-card-section>
                  <ImpWorkTable
                    @update="updateData"
                    :isReadOnly="isReadOnly"
                    :order-id="orderId"
                    class="q-ma-md"
                  ></ImpWorkTable>
                </q-card-section>
              </q-tab-panel>
  
              <!-- <q-tab-panel name="eform">
                <CheckEForm
                  @update="initCheckStatus"
                  class="q-pa-sm"
                ></CheckEForm>
              </q-tab-panel> -->
  
              <!-- <q-tab-panel name="finalCheck">
                <FinalCheckForm class="q-pa-sm"></FinalCheckForm>
              </q-tab-panel> -->
            </q-tab-panels>
          </q-step>
  
          <q-step
            active-color="indigo-8"
            :name="3"
            title="Final Check"
            :icon="`img:${finalcheckUrl}`"
            :disable="!checked"
          >
            <q-tab-panel name="finalCheck">
              <q-card-section>
           
                <FinalCheckForm
                  v-if="parts"
                  :order-id="orderId"
                  :isReadOnly="isReadOnly"
                  :is-parent="parts.is_parent"
                  :stock-code="parts?.stock_code"
                  :serial-no="parts?.serial_no"
                >
                  <TaskTable
                    v-if="parts"
                    :stock_code="parts.stock_code"
                    :isReadOnly="isReadOnly"
                    :parent="parts.is_parent"
                    @update="initCheckStatus"
                    :order-id="orderId"
                    role="checker"
                    display="final_tab"
                    isUpdateVeriAndEnd
                  ></TaskTable>
                </FinalCheckForm>
              </q-card-section>
            </q-tab-panel>
  
            <!-- <q-tab-panel name="finalCheck">
                  <q-card-section >
                    <TaskTable
                      v-if="parts"
                      :stock_code="parts.stock_code"
                      :isReadOnly="isReadOnly"
                      :parent="true"
                      @update="initCheckStatus"
                      :order-id="orderId"
                      role="tester"
                    ></TaskTable>
                  </q-card-section>
                </q-tab-panel> -->
          </q-step>
  
          <!-- v-if="!isReadOnly" -->
          <q-step
            active-color="indigo-8"
            :name="4"
            title="Job Complete"
            :icon="`img:${jobCompleteUrl}`"
            :disable="!checked"
          >
            <q-card-section>
              <JobCompleteDiag
                class="q-ml-md"
                :order-id="orderId"
                :isReadOnly="isReadOnly"
                @update="(data) => (checkStatus = data)"
                @after-job-complete="afterJobComplete"
                @redirect-to-final-check="goToTestResult"
              ></JobCompleteDiag>
            </q-card-section>
            <!--  <q-card-actions >
              <JobCompleteDiag
                class="q-ml-md"
                :order-id="orderId"
                @update="(data) => (checkStatus = data)"
                @after-job-complete="afterJobComplete"
              ></JobCompleteDiag>
            </q-card-actions> -->
          </q-step>
        </q-stepper>
      </div>
    </div>
  
    <q-dialog v-if="parts?.is_parent" v-model="reminder">
      <MyDialog
        title="notice"
        content="Please confirm the part detail before the order start"
        :ok="() => (reminder = false)"
      ></MyDialog>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { getStatusColor } from 'src/utils/getPublic';

import PartDetailTable from 'src/components/maintenance/PartDetailTable.vue';
import TaskTable from 'src/components/maintenance/TaskTable.vue';
import VerCheckTable from 'src/components/maintenance/VerCheckTable.vue';
import EdocTable from 'src/components/maintenance/EdocTable.vue';
import ImpWorkTable from 'src/components/maintenance/ImpWorkTable.vue';
import HtReplacementTable from 'src/components/maintenance/HtReplacementTable.vue';
import FinalCheckForm from 'src/components/maintenance/FinalCheckForm.vue';
import CheckEForm from 'src/components/maintenance/CheckEForm.vue';
import { parseTitle } from 'src/utils/stringUtils';
import { useRoute, useRouter } from 'vue-router';

import PartsMap from 'src/components/PartsMap.vue';
/* import RepairOrderPartsMap from 'src/components/RepairOrderPartsMap.vue'; */

import {
  getOrderDetail,
  getCheckStatus,
  getPrimaryPart,
} from 'src/services/repairService';
import { RepairOrder, RepairOrderCheckStatus, Parts } from 'src/services/type';
import JobCompleteDiag from 'src/components/maintenance/JobCompleteDiag.vue';
import OrderHistoryTable from 'src/components/orderHistory/OrderHistoryTable.vue';
import { useVersionStore } from 'src/stores/versionStore';
import OrderHardTimeReplacement from 'src/components/htReplacement/OrderHardTimeReplacement.vue';
import { confirmRepairOrder } from 'src/services/repairService';
import MyDialog from 'src/components/container/MyDialog.vue';
import OrderDetailPage from 'src/components/maintenance/OrderDetailPage.vue';
import EventLog from 'src/components/EventLog.vue';

// assets
import jobCompleteUrl from 'src/assets/style/jobComplete.png';
import finalcheckUrl from 'src/assets/style/finalcheck.png';
import maintenanceUrl from 'src/assets/style/maintenance.png';
import ObsolescenceTip from 'src/components/ObsolescenceTip.vue';

const versionStore = useVersionStore();
versionStore.init();
const route = useRoute();

const parts = ref<Parts>();

const reminder = ref(false);

const tab = ref('');
//get id from route
const orderId = parseInt(route.params.id as string);

const order = ref<RepairOrder>();

const isReadOnly = ref(false);

const showPartDetail = ref(true);

const checkStatus = ref<RepairOrderCheckStatus>();

const repairOrderPartsMap = ref<typeof PartsMap>();

const orderDetailDialog = ref(false);

const eventLogDialog = ref(false);

const step = ref(1);

const checked = ref();

const orderStatus = ref('Not Complete');

async function initParts() {
  const res = await getPrimaryPart(orderId);

  parts.value = res.data as Parts;
  if (!res.data.is_parent) {
    showPartDetail.value = false;
    checked.value = true
    tab.value = 'curTask';
  }
}

async function initCheckStatus() {
  const res = await getCheckStatus(orderId);
  console.log(res);
  
  checkStatus.value = res
  if (
    checkStatus.value.part_detail.outstanding == 0 &&
    checkStatus.value.current_task.outstanding == 0 &&
    checkStatus.value.software.outstanding == 0 &&
    checkStatus.value.hardware.outstanding == 0 &&
    checkStatus.value.edoc.outstanding == 0 &&
    checkStatus.value.hard_time_replacement.outstanding == 0 &&
    checkStatus.value.improvement_work.outstanding == 0 &&
    checkStatus.value.final_check.outstanding == 0
  ) {
    orderStatus.value = 'All Pass';
  }
}

async function initOrder() {
  const res = await getOrderDetail(orderId);
  
  if (res.data.status == 'CHECKED IN') {
    orderStatus.value = 'Not Complete';
  } else {
    orderStatus.value = res.data.status;
  }
  if (
    res.data.status == 'COMPLETE' ||
    res.data.status == 'COMPLETE*' ||
    res.data.status == 'CHECKOUT'
  ) {
    isReadOnly.value = true;
  }
  order.value = res.data as RepairOrder;
  // initCheckStatus()
  if (res.data.checked == 1) {
    checked.value = true;
    tab.value = 'curTask';
  } else if (res.data.checked == 0 && parts.value && parts.value.is_parent) {
    checked.value = false;
  }
  await initParts();
  if (res.data.checked == 0) {
    reminder.value = true;
  }
}

function afterEditOrderDetail() {
  orderDetailDialog.value = false
  initOrder() 
  initCheckStatus();
}

onMounted(() => {
  initCheckStatus();
});

const isJobComplete = false;

const router = useRouter();

function afterJobComplete() {
  if (isJobComplete) {
    router.push('/checkout');
  } else {
    isReadOnly.value = true;
    initOrder();
  }
}

async function updateChecked() {
  const res = await confirmRepairOrder(orderId, 1);
  if (res.data) {
    initOrder();
  }
}

function updateData() {
  if (repairOrderPartsMap.value) {
    repairOrderPartsMap.value.manualUpdate();
  }
  initCheckStatus();
}

function goToTestResult(){
  step.value = 3
}

onMounted(() => {
  initOrder();
});
</script>

<style scoped lang="scss">
.status-color-red {
  width: 42px;
  height: 18px;
  background-color: red;
  margin: 5px;
}

.header {
  font-size: 1.4rem;
  font-weight: 900;
  margin: 10px;
}

.card-action {
  display: flex;
  justify-content: center;
  align-items: center;
}

.p-status-field {
  font-size: 1.3rem;
  font-weight: 400;
  width: auto;
  margin-right: 5px;
}

.test {
  font-size: 100px;
}

/* .q-stepper__dot row flex-center q-stepper__line relative-position */
::v-deep(.q-stepper__dot) {
  width: 40px;
  height: 40px;
  font-size: 20px;
}

::v-deep(.q-stepper__step-inner) {
  padding: 0;
}

::v-deep(.q-stepper) {
  background-color: transparent;
}
.q-tab-panel {
  padding: 0;
}
::v-deep(.q-tabs) {
  background-color: #fff;
  margin: 0.5rem;
  padding: 0.5rem;
  border-radius: 1rem;
}
.maintenancePage {
  height: 100vh;
  overflow: scroll;
  padding-bottom: 120px;
}
</style>
